/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rest.client;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import org.apache.cxf.ext.logging.LoggingFeature;
import org.apache.cxf.feature.Feature;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * This is {@link RESTProxyClientFactory}.
 *
 * @author yisiqi
 * @since 1.0.0
 */
@SuppressWarnings("unused")
public class RESTProxyClientFactory {

	private static int port = 8080;

	public static <S> S build(Class<S> s, URL baseUrl, Object... providers) {
		return buildInternal(s, baseUrl.toString(), providers);
	}

	public static <S> S build(Class<S> s, String basePath, Object... providers) {
		return build(s, port, basePath, providers);
	}

	/**
	 * 创建用于E2E测试的Client，默认访问http://localhost
	 *
	 * @param s 服务接口
	 * @param port 随机端口
	 * @param basePath 服务发布的基路径
	 * @param providers 插件
	 * @param <S> 服务接口
	 *
	 * @return 服务调用代理
	 */
	public static <S> S build(Class<S> s, int port, String basePath, Object... providers) {
		return buildInternal(s, String.format("%s:%d%s", "http://localhost", port, basePath), providers);
	}

	private static <S> S buildInternal(Class<S> s, String baseUrlStr, Object... providers) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

		List<Object> providersList = new ArrayList<>(providers.length + 1);
		providersList.addAll(Arrays.asList(providers));
		providersList.add(new JacksonJsonProvider(mapper));

		List<Feature> featureList = new ArrayList<Feature>() {{
			add(new LoggingFeature());
		}};

		return JAXRSClientFactory.create(baseUrlStr, s, providersList, featureList, null);
	}

	protected static void overrideServerPort(int port) {
	    RESTProxyClientFactory.port = port;
    }

}
